import os
import json
import time
import requests


def DownloadVideo(video_name: str, video_date: str, video_download_url: str, video_save_path: str):
    print("正在下载", video_name)
    # 设置请求头
    headers = {"Proxy-Connection": "keep-alive"}
    # 获取文件后缀
    file_suffix = FileSuffix(video_download_url)
    # 组装文件名
    file_name = video_date + " " + video_name + "." + file_suffix
    # 获取文件数据
    response = requests.get(url=video_download_url, stream=True)
    # 获取文件大小
    Length = float(response.headers['content-length'])
    # 设置文件保存路径
    file_path = os.path.join(video_save_path, file_name)
    # 写入文件
    file = open(file_path, "wb")
    # 设置数量
    count = 0
    count_tmp = 0
    time1 = time.time()
    for chunk in response.iter_content(chunk_size=512):
        # 判断
        if chunk:
            file.write(chunk)
            count += len(chunk)
            if time.time() - time1 > 2:
                # 设置百分比
                percentage = count / Length * 100
                # 下载速度
                Speed = (count - count_tmp) / 1024 / 1024 / 2
                count_tmp = count
                print("正在下载:" + file_name, end="")
                print("文件比例:" + formatFloat(percentage) + "%", end="")
                print("下载速度:" + formatFloat(Speed) + "M/S")
                time1 = time.time()
    file.flush()
    file.close()
    print("下载完成")


# 获取文件后缀
def FileSuffix(url: str):
    # 获取文件
    files = str(url).split("/")
    files = files[-1]
    # 获取后缀
    suffix = files.split(".")
    return suffix[-1]


def formatFloat(num):
    return '{:.2f}'.format(num)


if __name__ == '__main__':
    file_path = os.path.join("E:\\", "猫咪AV数据", "在线视频", "短视频区")
    # 打开文件
    json_file = open(os.path.join(".", "在线视频", "短视频区.json"), encoding="UTF-8")
    data = json.load(json_file)
    for i in data:
        print(i)
        DownloadVideo(video_name=i["video_name"], video_date=i["video_date"],
                      video_download_url=i["video_download_url"], video_save_path=file_path)
        time.sleep(3)
